/*
 * create:2016年4月7日 上午8:04:52
 * author:wangds  
 */
package com.cxkj.shop.utils;

import java.security.MessageDigest;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;

import com.tencent.common.MD5;

/**
 * .
 * @author wangds
 *
 */
public class WxSignUtils {
  
  public static String MD5Encode(String origin) {
    String resultString = null;
    try {
        resultString = origin;
        MessageDigest md = MessageDigest.getInstance("MD5");
       // resultString = byteArrayToHexString(md.digest(resultString.getBytes()));//原文件内容，可能原因是：win2003时系统缺省编码为GBK，win7为utf-8
        resultString = MD5.byteArrayToHexString(md.digest(resultString.getBytes("utf-8")));//正确的写法
    } catch (Exception e) {
        e.printStackTrace();
    }
    return resultString;
}

    @SuppressWarnings("rawtypes")
    public static String createSign(SortedMap<String,Object> parameters,String key){  
        StringBuffer sb = new StringBuffer();  
        Set es = parameters.entrySet();//所有参与传参的参数按照accsii排序（升序）  
        Iterator it = es.iterator();  
        while(it.hasNext()) {  
            Map.Entry entry = (Map.Entry)it.next();  
            String k = (String)entry.getKey();  
            Object v = entry.getValue();  
            if(null != v && !"".equals(v)   
                    && !"sign".equals(k) && !"key".equals(k)) {  
                sb.append(k + "=" + v + "&");  
            }  
        }  
        sb.append("key=" + key);
        String sign = MD5Encode(sb.toString()).toUpperCase();  
        return sign;  
    }
      
    public static String getNonceStr() {
        Random random = new Random();
        return MD5.MD5Encode(String.valueOf(random.nextInt(10000)));
    }
  
    public static String getTimeStamp() {
        return String.valueOf(System.currentTimeMillis() / 1000);
    }
  

}
